let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');

/**
 * 查询考卷数据 by p 2018-06-11
 *
 * 按条件查询考卷数据
 *
 */
router.get('/', filter.authorize, function (req, res, next) {
    let params = req.query;

    var sql = "";
    var datas = [];
    let user = req.session.user;

    if (user.roleId !== 1) {
        sql = "userId = ?";
        datas.push(user.id);
    }

    if (params.examId > 0) {
        sql += (sql === "" ? "" : " and ") + "examId = ?";
        datas.push(params.examId);
    }

    req.app.db.query("select * from paper " + (sql === "" ? "" : " where ") + sql + " order by id desc", datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        res.json({"success": true, "data": results, "totalCount": results.length});
    });
});

/**
 * 查看考卷数据 by p 2018-06-11
 *
 * 按id查看指定的考卷信息
 */
router.get('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;

    var datas = [];
    var user = req.session.user;

    var sql = "where id = ?";
    datas.push(params.id);

    if (user.roleId !== 1) {
        sql += " and userId = ?";
        datas.push(user.id);
    }

    req.app.db.query("select * from paper " + sql + " order by id desc", datas, function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "当前用户无法查看此条试卷信息！"});
            return;
        }

        res.json({"success": true, "data": results[0]});
    });
});

/**
 * 删除考卷信息 by v 2018-06-11
 *
 * 按id删除指定的考卷信息
 */
router.delete('/:id', filter.authorize, function (req, res, next) {
    let params = req.params;
    let user = req.session.user;

    // 查询试卷
    req.app.db.query("select * from paper where id = ?", [params.id], function (err, results, fields) {
        if (err) {
            res.json({"success": false, "message": global.databaseErr, "detail": err});
            return;
        }

        if (results.length === 0) {
            res.json({"success": false, "message": "试卷信息错误！"});
            return;
        }

        if (user.id !== 1 && results[0].userId !== user.id) {
            res.json({"success": false, "message": "非录入用户不能删除试卷信息！"});
            return;
        }

        // 删除试卷
        req.app.db.query('delete from paper where id = ?', [params.id], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            res.json({"success": true, "message": global.deleteMsg});
        });
    });
});

module.exports = router;